<?php

namespace app\common\command\task;

use app\common\model\OrderBonusItem;
use app\common\model\OrderBonusSettlement;
use think\facade\Db;

/**
 *
 * php think cron orderBonusSettlementProcess
 */
class OrderBonusSettlementProcess
{

    /**
     * invoke
     * @throws
     */
    public function invoke()
    {
        $this->execute();
    }

    /**
     * execute
     * @return void
     * @throws
     */
    private function execute()
    {
        // 查询待结算金额大于10元的代理
        $threeDaysAgoTime = strtotime(date('Y-m-d', strtotime('-7 days')));

        // 查询条件
        $where = [
            ['is_settlement', '=', 0],
            ['status', '=', 1],
            ['is_build_settlement_order', '=', 0],
            ['create_time', '<=', $threeDaysAgoTime],
        ];
        $having = 'bonus_amount >= 10';

        // 查询字典
        $field = 'agent_id,sum( bonus_amount ) AS bonus_amount';

        // 查询数据
        $agentList = app(OrderBonusItem::class)->where($where)->field($field)->group('agent_id')->having($having)->select()->toArray();
        if (!$agentList) {
            echo '暂无需要处理的数据';
            return;
        }

        // 循环处理数据
        foreach ($agentList as $key => $item) {
            $this->executeItem($item);
        }
    }

    /**
     * executeItem
     * @param $item
     * @return void
     */
    private function executeItem($item)
    {
        // 提取参数
        $agent_id = $item['agent_id'];

        // 开启事务
        Db::transaction(function () use ($agent_id) {
            // 生成结算单
            $orderBonusSettlement = new OrderBonusSettlement();
            $orderBonusSettlement->createOrder($agent_id);
        });
    }
}